package cn.felord.oss;

import io.minio.*;

import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * @author felord.cn
 * @since 2020/8/24 20:01
 */
public class MinioStorage implements Storage {

    private final MinioClient minioClient;

    public MinioStorage(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    @Override
    public void putObject(String bucketName, String objectName, InputStream inputStream, String contentType) throws Exception {
        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(inputStream, -1, -1)
                .contentType(contentType)
                .build();

        minioClient.putObject(objectArgs);
    }

    @Override
    public InputStream getObject(String bucketName, String objectName) throws Exception {
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        return minioClient.getObject(getObjectArgs);
    }

    @Override
    public String getObjectUrl(String bucketName, String objectName) throws Exception {
        GetPresignedObjectUrlArgs objectUrlArgs = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        return minioClient.getPresignedObjectUrl(objectUrlArgs);
    }

    @Override
    public void removeObject(String bucketName, String objectName) throws Exception {
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        minioClient.removeObject(removeObjectArgs);
    }
}
